# -*- coding: utf-8 -*-
"""
Created on Fri Jun  5 08:46:53 2020

@author: guguoqiang
"""

import numpy as np
import cv2
import matplotlib.pyplot as plt
from numpy.fft import *
def preprocess(img,m):
    row=len(img)
    column=len(img[0])
    img=img[0:int(row/m)*m,0:int(column/m)*m]
    return img
def create_module(m,n):
    result=np.zeros((m,m))
    if n==1:
        result[0,0]=1
    if n==3:
        for i in range(2):
            for j in range(2-i):
                result[i,j]=1
    if n==6:
        for i in range(3):
            for j in range(3-i):
                result[i,j]=1
    if n==15:
        for i in range(5):
            for j in range(5-i):
                result[i,j]=1
    return result  
def dct(m):
    T=np.zeros((m,m))
    for i in range(0,m):
        for j in range(0,m):
            if i==0:
                a=np.sqrt(1.0/m)
            else:
                a=np.sqrt(2.0/m)
            T[i,j]=a*np.cos(np.pi*(j+0.5)*i/m)
    return T
def area_encode(area,T,module):
    result=T.dot(area).dot(np.transpose(T))
    return result*module
def area_decode(area,T):
    result=np.transpose(T).dot(area).dot(T)
    return result
def encode(img,m,T,module):
    row=len(img)
    column=len(img[0])
    result=np.zeros((row,column))
    for i in range(int(row/m)):
        for j in range(int(column/m)):
            area=img[m*i:m*(i+1),m*j:m*(j+1)]
            result[m*i:m*(i+1),m*j:m*(j+1)]=area_encode(area,T,module)
    return result
def decode(result,m,T):
    row=len(result)
    column=len(result[0])
    img=np.zeros((row,column))
    for i in range(int(row/m)):
        for j in range(int(column/m)):
            area=result[m*i:m*(i+1),m*j:m*(j+1)]
            img[m*i:m*(i+1),m*j:m*(j+1)]=area_decode(area,T)
    return img

img=cv2.imread("images.jpg",cv2.IMREAD_COLOR)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
m=8
module=create_module(m,1)
T=dct(m)
gray=preprocess(gray,m)
encode_img=encode(gray,m,T,module)
decode_img=decode(encode_img,m,T)
print('原图')
plt.figure()
plt.imshow(gray)
print('变换编码后的图像')
plt.figure()
plt.imshow(encode_img)
print('解码后的图像')
plt.figure()
plt.imshow(decode_img)